﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class KnapsackComponent
{
    public Action< IKnapsackItem> onSelect;
    public Action<DynamicInfinityItem > onUpdate;

    List<IKnapsackItem> list = new List<IKnapsackItem>();
    DynamicInfinityListRenderer dynamicInfinityListRenderer;


    public void Initialize(DynamicInfinityListRenderer dynamicInfinityListRenderer)
    {
        if (dynamicInfinityListRenderer == null)
            throw new Exception("dynamicInfinityListRenderer is null");
        this.dynamicInfinityListRenderer = dynamicInfinityListRenderer;
        dynamicInfinityListRenderer.InitRendererList(OnSelect, OnUpdate);
        dynamicInfinityListRenderer.SetDataProvider(list);
    }

    public void Add(IKnapsackItem knapsackItem)
    {
        _Add(knapsackItem);
        dynamicInfinityListRenderer.RefreshDataProvider();
    }

    public void AddRange(IKnapsackItem []knapsackItem)
    {
        for(int i=0;i<knapsackItem.Length;i++)
        {
            _Add(knapsackItem[i]);
        }
        dynamicInfinityListRenderer.RefreshDataProvider();
    }

    void _Add(IKnapsackItem knapsackItem)
    {
        if(knapsackItem.IsSuperposition())
        {
            var index = list.FindIndex(item => item.GetFixedId() == knapsackItem.GetId());
            if(index == -1)
            {
                knapsackItem.SetItemId(0);
                list.Add(knapsackItem);
            }
            else
            {
                list[index].SetNumber(list[index].GetNumber() + knapsackItem.GetNumber());
            }
        }
        else
        {
            int itemId=0;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].GetFixedId() == knapsackItem.GetId())
                {
                    itemId = Math.Max(itemId,list[i].GetItemId());
                }
            }
            knapsackItem.SetItemId(itemId+1);
            list.Add(knapsackItem);
        }
    }

    public void RemoveAt(int index)
    {
        list.RemoveAt(index);
        dynamicInfinityListRenderer.RefreshDataProvider();
    }

    public void Remove(IKnapsackItem knapsackItem)
    {
        list.Remove(knapsackItem);
        dynamicInfinityListRenderer.RefreshDataProvider();
    }

    public void Clear()
    {
        list.Clear();
        dynamicInfinityListRenderer.RefreshDataProvider();
    }

    void OnSelect(DynamicInfinityItem item)
    {
        if(onSelect!= null)
        {
            onSelect.Invoke( item.GetData<IKnapsackItem>());
        }
    }

    void OnUpdate(DynamicInfinityItem item)
    {
        if(onUpdate!=null)
        {
            onUpdate.Invoke(item);
        }
    }
}
